<template>
  <div class="store-reconciliation">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">🏪 门店对账</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleGenerate">
              <el-icon><DocumentAdd /></el-icon>
              生成对账单
            </el-button>
            <el-button type="success" @click="handleBatchConfirm">
              <el-icon><Select /></el-icon>
              批量确认
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="门店名称">
          <el-input v-model="searchForm.storeName" placeholder="请输入门店名称" clearable />
        </el-form-item>
        <el-form-item label="对账周期">
          <el-date-picker
            v-model="searchForm.period"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="对账状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待对账" value="pending" />
            <el-option label="对账中" value="checking" />
            <el-option label="有差异" value="difference" />
            <el-option label="已确认" value="confirmed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="32"><Shop /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">门店总数</div>
              <div class="stat-value">{{ totalStores }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="32"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">待对账</div>
              <div class="stat-value">{{ pendingCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="32"><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">有差异</div>
              <div class="stat-value difference">{{ differenceCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="32"><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">对账金额</div>
              <div class="stat-value">¥{{ totalAmount.toLocaleString() }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchConfirm">批量确认</el-button>
              <el-button size="small" type="warning" @click="handleBatchExport">批量导出</el-button>
              <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 对账列表 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="对账单号" width="150" />
        <el-table-column prop="storeName" label="门店名称" width="180" />
        <el-table-column prop="storeCode" label="门店编码" width="120" />
        <el-table-column prop="period" label="对账周期" width="180">
          <template #default="{ row }">
            {{ row.startDate }} 至 {{ row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="systemAmount" label="系统金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.systemAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="storeAmount" label="门店报账" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.storeAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="difference" label="差异金额" width="120">
          <template #default="{ row }">
            <span :class="getDifferenceClass(row.difference)">
              {{ row.difference > 0 ? '+' : '' }}¥{{ Math.abs(row.difference).toLocaleString() }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">查看明细</el-button>
            <el-button 
              v-if="row.status === 'pending' || row.status === 'difference'" 
              link 
              type="success" 
              @click="handleConfirm(row)"
            >
              确认对账
            </el-button>
            <el-button link type="warning" @click="handleAdjust(row)">差异调整</el-button>
            <el-button link type="info" @click="handleExport(row)">导出</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 生成对账单对话框 -->
    <el-dialog 
      v-model="generateDialogVisible" 
      title="生成对账单"
      width="600px"
    >
      <el-form :model="generateForm" :rules="generateRules" ref="generateFormRef" label-width="100px">
        <el-form-item label="选择门店" prop="storeIds">
          <el-select 
            v-model="generateForm.storeIds" 
            multiple 
            placeholder="请选择门店"
            style="width: 100%"
          >
            <el-option label="全部门店" value="all" />
            <el-option label="深圳旗舰店" value="1" />
            <el-option label="上海分店" value="2" />
            <el-option label="北京分店" value="3" />
            <el-option label="广州分店" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="对账周期" prop="period">
          <el-date-picker
            v-model="generateForm.period"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="对账类型" prop="type">
          <el-radio-group v-model="generateForm.type">
            <el-radio label="sales">销售对账</el-radio>
            <el-radio label="inventory">库存对账</el-radio>
            <el-radio label="finance">财务对账</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="generateForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGenerateSubmit">生成</el-button>
      </template>
    </el-dialog>

    <!-- 对账明细对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="对账明细"
      width="1200px"
    >
      <div class="detail-header">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="对账单号">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="门店名称">{{ currentDetail.storeName }}</el-descriptions-item>
          <el-descriptions-item label="对账周期">
            {{ currentDetail.startDate }} 至 {{ currentDetail.endDate }}
          </el-descriptions-item>
          <el-descriptions-item label="系统金额">
            <span class="amount-highlight">¥{{ currentDetail.systemAmount?.toLocaleString() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="门店报账">
            <span class="amount-highlight">¥{{ currentDetail.storeAmount?.toLocaleString() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="差异金额">
            <span :class="getDifferenceClass(currentDetail.difference)">
              {{ currentDetail.difference > 0 ? '+' : '' }}¥{{ Math.abs(currentDetail.difference || 0).toLocaleString() }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-tabs v-model="detailTab" class="detail-tabs">
        <el-tab-pane label="销售明细" name="sales">
          <el-table :data="detailData.sales" border max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="orderCount" label="订单数" width="100" />
            <el-table-column prop="systemAmount" label="系统金额" width="120">
              <template #default="{ row }">
                ¥{{ row.systemAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="storeAmount" label="门店金额" width="120">
              <template #default="{ row }">
                ¥{{ row.storeAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="difference" label="差异" width="120">
              <template #default="{ row }">
                <span :style="{ color: row.difference !== 0 ? '#f56c6c' : '#67c23a' }">
                  {{ row.difference > 0 ? '+' : '' }}¥{{ Math.abs(row.difference).toLocaleString() }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="收款明细" name="payment">
          <el-table :data="detailData.payment" border max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="paymentMethod" label="收款方式" width="120" />
            <el-table-column prop="systemAmount" label="系统金额" width="120">
              <template #default="{ row }">
                ¥{{ row.systemAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="storeAmount" label="门店金额" width="120">
              <template #default="{ row }">
                ¥{{ row.storeAmount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="difference" label="差异" width="120">
              <template #default="{ row }">
                <span :style="{ color: row.difference !== 0 ? '#f56c6c' : '#67c23a' }">
                  {{ row.difference > 0 ? '+' : '' }}¥{{ Math.abs(row.difference).toLocaleString() }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="费用明细" name="expense">
          <el-table :data="detailData.expense" border max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="type" label="费用类型" width="150" />
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 差异调整对话框 -->
    <el-dialog 
      v-model="adjustDialogVisible" 
      title="差异调整"
      width="600px"
    >
      <el-form :model="adjustForm" label-width="100px">
        <el-form-item label="差异金额">
          <el-input-number 
            v-model="adjustForm.amount" 
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="调整原因">
          <el-select v-model="adjustForm.reason" placeholder="请选择原因">
            <el-option label="系统错误" value="system_error" />
            <el-option label="门店漏报" value="store_missing" />
            <el-option label="退换货" value="return" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="调整说明">
          <el-input 
            v-model="adjustForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细说明调整原因" 
          />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            action="#"
            :limit="3"
            :file-list="adjustForm.files"
          >
            <el-button type="primary">上传凭证</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdjustSubmit">提交调整</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DocumentAdd, Select, Shop, Document, Warning, Money
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  storeName: '',
  period: null,
  status: ''
})

// 选中的行
const selectedRows = ref([])

// 统计数据
const totalStores = ref(12)
const pendingCount = ref(5)
const differenceCount = ref(3)
const totalAmount = ref(1245678)

// 表格数据
const tableData = ref([
  {
    id: 'DZ202401001',
    storeName: '深圳旗舰店',
    storeCode: 'SZ001',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    systemAmount: 1256789,
    storeAmount: 1256789,
    difference: 0,
    status: 'confirmed',
    createTime: '2024-01-31 18:00:00'
  },
  {
    id: 'DZ202401002',
    storeName: '上海分店',
    storeCode: 'SH001',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    systemAmount: 856234,
    storeAmount: 854500,
    difference: 1734,
    status: 'difference',
    createTime: '2024-01-31 18:00:00'
  },
  {
    id: 'DZ202401003',
    storeName: '北京分店',
    storeCode: 'BJ001',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    systemAmount: 945678,
    storeAmount: 946000,
    difference: -322,
    status: 'checking',
    createTime: '2024-01-31 18:00:00'
  },
  {
    id: 'DZ202401004',
    storeName: '广州分店',
    storeCode: 'GZ001',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    systemAmount: 756234,
    storeAmount: 0,
    difference: 756234,
    status: 'pending',
    createTime: '2024-01-31 18:00:00'
  }
])

// 对账明细数据
const currentDetail = ref({})
const detailTab = ref('sales')
const detailData = reactive({
  sales: [
    { date: '2024-01-01', orderCount: 145, systemAmount: 45678, storeAmount: 45678, difference: 0, remark: '' },
    { date: '2024-01-02', orderCount: 156, systemAmount: 48900, storeAmount: 48500, difference: 400, remark: '1笔退货未录入' }
  ],
  payment: [
    { date: '2024-01-01', paymentMethod: '现金', systemAmount: 12000, storeAmount: 12000, difference: 0 },
    { date: '2024-01-01', paymentMethod: '微信', systemAmount: 23678, storeAmount: 23678, difference: 0 }
  ],
  expense: [
    { date: '2024-01-01', type: '租金', amount: 15000, remark: '1月份租金' },
    { date: '2024-01-05', type: '水电费', amount: 2500, remark: '1月份水电' }
  ]
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 4
})

// 对话框
const generateDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const adjustDialogVisible = ref(false)
const generateFormRef = ref(null)

// 生成表单
const generateForm = reactive({
  storeIds: [],
  period: null,
  type: 'sales',
  remark: ''
})

const generateRules = {
  storeIds: [{ required: true, message: '请选择门店', trigger: 'change' }],
  period: [{ required: true, message: '请选择对账周期', trigger: 'change' }]
}

// 调整表单
const adjustForm = reactive({
  amount: 0,
  reason: '',
  description: '',
  files: []
})

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    pending: 'info',
    checking: 'warning',
    difference: 'danger',
    confirmed: 'success'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待对账',
    checking: '对账中',
    difference: '有差异',
    confirmed: '已确认'
  }
  return map[status] || status
}

// 获取差异样式
const getDifferenceClass = (diff) => {
  if (diff === 0) return 'difference-zero'
  if (diff > 0) return 'difference-positive'
  return 'difference-negative'
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.storeName = ''
  searchForm.period = null
  searchForm.status = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 生成对账单
const handleGenerate = () => {
  generateDialogVisible.value = true
}

const handleGenerateSubmit = () => {
  generateFormRef.value.validate((valid) => {
    if (valid) {
      console.log('生成对账单:', generateForm)
      ElMessage.success('对账单生成成功')
      generateDialogVisible.value = false
      handleSearch()
    }
  })
}

// 查看明细
const handleViewDetail = (row) => {
  currentDetail.value = row
  detailDialogVisible.value = true
}

// 确认对账
const handleConfirm = (row) => {
  ElMessageBox.confirm(`确定要确认对账单 "${row.id}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('对账确认成功')
  })
}

// 差异调整
const handleAdjust = (row) => {
  adjustForm.amount = row.difference
  adjustDialogVisible.value = true
}

const handleAdjustSubmit = () => {
  console.log('提交调整:', adjustForm)
  ElMessage.success('差异调整提交成功')
  adjustDialogVisible.value = false
}

// 导出
const handleExport = (row) => {
  ElMessage.success(`正在导出对账单 ${row.id}`)
}

// 批量操作
const handleBatchConfirm = () => {
  ElMessage.success('批量确认成功')
  selectedRows.value = []
}

const handleBatchExport = () => {
  ElMessage.success('批量导出成功')
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条对账单吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
  })
}
</script>

<style scoped>
.store-reconciliation {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.difference {
  color: #f56c6c;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.difference-zero {
  color: #67c23a;
  font-weight: bold;
}

.difference-positive {
  color: #f56c6c;
  font-weight: bold;
}

.difference-negative {
  color: #e6a23c;
  font-weight: bold;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.detail-header {
  margin-bottom: 20px;
}

.amount-highlight {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.detail-tabs {
  margin-top: 20px;
}
</style>

